package org.example.jdbc;

import org.example.Main;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBCReg {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection()) {
            //接收用户名和密码
            Scanner scanner = new Scanner(System.in);
            System.out.println("用户名：");
            String username = scanner.nextLine();
            System.out.println("密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称");
            String nickname = scanner.nextLine();
            System.out.println("输入年龄");
            int age = scanner.nextInt();
            String sql = "SELECT username FROM userinfo WHERE username = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet r = ps.executeQuery();
            if (r.next()){
                System.out.println("用户名被占用");
            }else {
                String sql1 = "INSERT INTO userinfo (username , password , nickname , age) VALUES (?,?,?,?)";
                PreparedStatement ps1 = connection.prepareStatement(sql1);
                ps1.setString(1,username);
                ps1.setString(2,password);
                ps1.setString(3,nickname);
                ps1.setInt(4,age);
                ps1.executeUpdate();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}